import { exec } from "child_process";
import Data from "../components/Data.js";

const _path = process.cwd();


let timer
// 更新插件内容
export async function updateShinonePlugin(e = {}) {
  if (!e.isMaster) {
    e.reply("哒咩，你可不是老娘的master");
    return true;
  }
  
  let command = "git  pull";
  if(e.msg.includes('强制')) {
    command = 'git  checkout . && git  pull'
  }
  e.reply("马上给你更新，稍等一下");
  exec(command, { cwd: `${_path}/plugins/shinone-plugin/` }, function (error, stdout, stderr) {
    if (/Already up[ -]to[ -]date/.test(stdout)) {
      e.reply("没有可以更新的内容呢");
      return true;
    }
    if (error) {
      e.reply(`更新失败了呜呜呜\nError code: ${error.code}\n${error.stack}\n等会再试试吧`);
      return true;
    }
    timer && clearTimeout(timer)
    Data.setCacheJSON('miao:restart-msg', {
      msg: '重启成功，筱音插件已经生效',
      qq: e.user_id
    }, 30)
    timer = setTimeout(function () {
      let command = 'pnpm run start'
      if (process.argv[1].includes('pm2')) {
        command = 'pnpm run restart'
      }
      exec(command, function (error, stdout, stderr) {
        if (error) {
          e.reply('自动重启失败，请手动重启。\nError code: ' + error.code + '\n' + error.stack + '\n')
          Bot.logger.error(`重启失败\n${error.stack}`)
          return true
        } else if (stdout) {
          Bot.logger.mark('重启成功，运行已转为后台，查看日志请用命令：pnpm run log')
          Bot.logger.mark('停止后台运行命令：pnpm stop')
          process.exit()
        }
      })
    }, 1000)
  });

  return true;
}